#include "clienttcp.h"

clienttcp::clienttcp(QObject *parent) :
    QObject(parent)
{
    tcpPort = 6666;
    serverAddress  = getLocalHostIP();

    connect(&tcpSocket, SIGNAL(connected()),
            this, SLOT(sendMessage()));

    connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
}

void clienttcp::newConnect()
{
    tcpSocket.abort();
    tcpSocket.connectToHost(serverAddress,tcpPort);
}

void clienttcp::sendMessage()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    out.setVersion(QDataStream::Qt_4_6);

    out << serverAddress;
    out << message;

    tcpSocket.write(block);
    qDebug() << serverAddress << message;
}

void clienttcp::displayError(QAbstractSocket::SocketError)
{
    qDebug() << tcpSocket.errorString();
}

void clienttcp::send(const QString &meg)
{
    message = meg;
    newConnect();
}

void clienttcp::setPort(const qint16 &port)
{
    tcpPort = port;
}

void clienttcp::setAddress(const QString &address)
{
    serverAddress = address;
}

QString clienttcp::getLocalHostIP()
{
    QList<QNetworkInterface> InterfaceIpList = QNetworkInterface::allInterfaces();
    for(int i = 0; i < InterfaceIpList.length(); i++)
    {
        if(InterfaceIpList[i].isValid())
        {
            foreach(QNetworkAddressEntry addressE , InterfaceIpList[i].addressEntries() )
            {
                if(addressE.ip().protocol() == QAbstractSocket::IPv4Protocol &&
                   addressE.broadcast()!= QHostAddress::Null
                   )
                {
                    return addressE.ip().toString();
                }
            }
        }
    }

    return QString("");
}
